package scene

import (
	"math"
)

type Grid struct {
	id       int      // 格子的唯一标识符
	entities []Entity //格子中的实体由层级锁保护，减少加锁释放
}

func NewGrid(id int) *Grid {
	return &Grid{id: id, entities: make([]Entity, 0)}
}

// GetID 获取格子的唯一标识符
func (s *Grid) GetID() int {
	return s.id
}

func (s *Grid) Count(et EntityType) int {
	if et == EntityTypeNone {
		return len(s.entities)
	}
	count := 0
	for _, entity := range s.entities {
		if entity.GetType() == et {
			count++
		}
	}
	return count
}

// Add 添加玩家到格子
func (s *Grid) Add(p Entity) {
	s.entities = append(s.entities, p)
}
func (s *Grid) Update() {
	for _, entity := range s.entities {
		entity.Update()
	}
}

// Remove 从格子移除玩家
func (s *Grid) Remove(p Entity) bool {
	for i, entity := range s.entities {
		if entity.GetID() == p.GetID() {
			// 从entities中删除该实体
			s.entities = append(s.entities[:i], s.entities[i+1:]...)
			return true
		}
	}
	return false
}

// GetEntities 获取格子中视野内所有实体
func (s *Grid) GetEntities(x, y float64, radius float64, et EntityType) []Entity {
	var entities []Entity
	for _, entity := range s.entities {
		if et != EntityTypeNone && entity.GetType() != et {
			continue
		}
		// 计算实际距离
		dx := math.Abs(entity.GetX() - x)
		dy := math.Abs(entity.GetY() - y)
		distance := dx*dx + dy*dy

		if distance <= radius*radius {
			entities = append(entities, entity)
		}
	}
	return entities
}

// GetNearEntities 获取格子中视野内所有实体
func (s *Grid) GetNearEntities(p Entity, radius float64, et EntityType) []Entity {
	x, y := p.GetX(), p.GetY()
	var entities []Entity
	for _, entity := range s.entities {
		if entity.GetID() == p.GetID() {
			continue // 跳过自己
		}
		if et != EntityTypeNone && entity.GetType() != et {
			continue
		}
		// 计算实际距离
		dx := math.Abs(entity.GetX() - x)
		dy := math.Abs(entity.GetY() - y)
		distance := dx*dx + dy*dy

		if distance <= radius*radius {
			entities = append(entities, entity)
		}
	}
	return entities
}
